<!-- 等待接口新增数据就好了 -->
<template>
  <div>
    <el-card>
    <el-table
        :data=tableData
        border
        style="width: 100%">
        <el-table-column
            fixed
            prop="courseId"
            label="课程号"
            width="150">
        </el-table-column>
        <el-table-column
            prop="courseName"
            label="课程"
            width="150">
        </el-table-column>
        <el-table-column
            prop="teacherName"
            label="教师名称"
            width="150">
        </el-table-column>
        <el-table-column
            prop="studentName"
            label="学生名称"
            width="150">
        </el-table-column>
        <el-table-column
            prop="score"
            label="成绩"
            width="150">
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete()"
              >删除</el-button
            >
          
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :page-sizes="[1, 2, 3]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :total="firstFrom.total">
      </el-pagination>
    </el-card>
    <!-- 编辑表单弹窗 -->
    <el-dialog
        title="编辑老师信息"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
      <el-form style="width: 60%" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="课程Id" prop="courseId">
          <el-input v-model="ruleForm.courseId" :value="ruleForm.courseId" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="ruleForm.courseName" :value="ruleForm.courseName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="学生Id" prop="studentId">
          <el-input v-model="ruleForm.studentId" :value="ruleForm.studentId" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="学生名" prop="studentName">
          <el-input v-model="ruleForm.studentName" :value="ruleForm.studentName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="分数" prop="score">
          <el-input v-model.number="ruleForm.score" :value="ruleForm.score"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button @click="cancelEdit">取 消</el-button>
          <el-button type="primary" @click="updateEdit(ruleForm)">确定</el-button>
        </el-form-item>
      </el-form>
      </el-dialog>
    <p>
      平均成绩：{{ avg }}
    </p>
  </div>
</template>

<script>
export default {
  methods: {
    
  },
  data() {
    return {
      firstFrom:{
        // 用于保存初始的条数
      total:0,
      },
      pageFrom:{
        page: 1,
        pageSize: 2,
        teacherId:'',
        // 要传给后端的数据,还有一些其他的数据
      },
      // 用于成绩查询的检索
      studentId:'',
      studentName:'',
      teacherName:'',
      courseId:'',
      courseName:'',
      total: 0,
      tableData: [
        // 表格数据

      ],
      ruleForm: {
      courseId: '',
      courseName: '',
      score: 0,
      studentId: '',
      studentName: '',
      teacherId: '',
      teacherName: ''
      },
      rules: {
      courseId: [{ required: true, message: "请填写课程编号" },],
      courseName: [{ required: true, message: "请填写课程名称" }],
      studentId: [{ required: true, message: "请填写学生Id" }],
      studentName: [{ required: true, message: "请填写学生名称" }],
      score: [{ required: true, message: "请填写成绩" }],
      // Remove the previous student-related validation rules
        
      },
      avg:0,
      dialogFormVisible:false,
    }
  },
  created() {
    if(localStorage.getItem("type") !== 'teacher'){this.$router.push(`/login`);this.$message.error('你不是老师');}
    // 初始化操作
    this.name = localStorage.getItem('name');
    this.pageFrom.teacherId = localStorage.getItem('teacherId');//要有teacherId
    this.getFirstGrade();
    this.ruleFrom.teacherName = localStorage.getItem('name');
    this.pageFrom.teacherId = localStorage.getItem('teacherId');//要有teacherId
  },
  // eslint-disable-next-line no-dupe-keys
  methods: {
     // 数据分页
    handleCurrentChange(currentPage) {
      this.pageFrom.page = currentPage;
      this.getOwnGrade()
      // 每次更改都要请求一次tabledata数据，在后端做数据分页！>.<！
    },
    handleSizeChange(size) {
      this.pageFrom.pageSize = size;
      this.getOwnGrade()
      // 每次更改都要请求一次tabledata数据，在后端做数据分页！>.<！
    },
    // 获取课程信息表
    async getOwnGrade() {
    console.log(JSON.stringify(this.pageFrom));
    // JSON化
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'token':`${localStorage.getItem("token")}`
      }
    };
    try {
      const { data: res } = await this.$http.post(`api/teacher/grade/page`,JSON.stringify(this.pageFrom),config);
      console.log(res.data);
      if (res.status !== 500) {
        this.$message.success('成功获取学生们的成绩');
        this.tableData=res.data.records;
      } else {
        this.$message.error('获取失败');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('请求失败');
  }
    },
    // 获取初始信息表
    async getFirstGrade() {
      this.pageFrom.pageSize=10
    // JSON化
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'token':`${localStorage.getItem("token")}`// Custom request header
      }
    };
    try {
      const { data: res } = await this.$http.post(`api/teacher/grade/page`,JSON.stringify(this.pageFrom),config);
      console.log(res.data);
      if (res.status !== 500) {
        this.$message.success('成功获取学生们的成绩');
        this.tableData=res.data.records;
        this.firstFrom.total = res.data.total; // 保存总条数
      } else {
        this.$message.error('获取失败');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('请求失败');
  }
    },
    async searchCourse() {
      // 在这里执行你想要的点击事件的逻辑,嗨哟啊修改
      console.log("点击了搜索按钮,要查询的课程ID是:" + JSON.stringify({...this.pageFrom, courseName: this.courseName}));
    // JSON化
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'token':`${localStorage.getItem("token")}`// Custom request header
      }
    };
    try {
      const { data: res } = await this.$http.get(`api/teacher/grade/page`,JSON.stringify({...this.pageFrom, courseName: this.courseName}),config);
      console.log(res.data);
      if (res.status !== 500) {
        this.$message.success('成功获取我的成绩');
        this.tableData=res.data.record;
        this.firstFrom.total = res.data.total; // 保存总条数
      } else {
        this.$message.error('获取失败');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('请求失败');
  }
    },
    handleDelete(){
      this.$message.error('请您去找管理员');
    },
    handleEdit(index,row){
      this.dialogFormVisible = true;
        this.ruleForm = { ...row };
    },
    // 保存编辑按钮
    async updateEdit(params) {
        if (confirm("是否确认所编辑的内容！")){
        console.log(JSON.stringify(params));
      // JSON化
      const config = {
        headers: {
          'Content-Type': 'application/json',
        'token':`${localStorage.getItem("token")}`// Custom request header
        }
      };
      try {
        const { data: res } = await this.$http.put(`api/teacher/grade/update`,JSON.stringify(params),config);
        console.log(res.data);
        if (res.status !== 500) {
          this.$message.success('成功编辑该学生成绩');
          // 重新调用获取表格的代码
          this.getFirstGrade();
          this.dialogFormVisible = false;
        } else {
          this.$message.error('编辑失败');
        }
      } catch (error) {
        // Handle request error
        console.error('Request Error:', error);
        this.$message.error('编辑1失败');
    }
  }
  },
      // 取消编辑按钮
      cancelEdit() {
        if (confirm("是否确认取消所编辑的内容！")) {
          this.dialogFormVisible = false;
        }
      },

  // 还要加上一个查询课程成绩的接口，接口名称一样的
  }
 
}
</script>